package com.hugh.blog_cache.fifter;

import com.hugh.common.data.LocalDateTimeUtils;
import com.hugh.common.enums.EnumSupport;
import com.hugh.common.enums.EnumSupportNumber;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Matcher;

import static java.util.stream.Collectors.joining;

/**
 * @Author: Hugh
 * @Date: 2020/5/25
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,
                RowBounds.class, ResultHandler.class})})
@Slf4j
@Component
public class MybatisSQLInterceptor implements Interceptor {

    /**
     * sql 慢于1秒的warning
     */
    private final static int WARNING_SQL_TIME  =1000;
    /**
     * sql 慢于2秒的error
     */
    private final static int ERROR_SQL_TIME  =2000;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();
        Object returnValue = null;
        long start = System.currentTimeMillis();
        String sql = "";
        try {
            try{
                sql = getSql(showSql(configuration, boundSql), sqlId);
            }catch (Exception e){

                log.info("sql parsing error, sqlId = {}", sqlId);
            }
            returnValue = invocation.proceed();
            long end = System.currentTimeMillis();
            long time = (end - start);

            if (time >= WARNING_SQL_TIME && time <= ERROR_SQL_TIME) {
                log.warn("[--->SQL耗时:{}ms],slow query warning, sql = {}", time, sql);
            } else if (time > ERROR_SQL_TIME) {
                log.error("[--->SQL耗时:{}ms],slow query error, sql = {}", time, sql);
            } else {
                log.info("[--->SQL耗时:{}ms]{}", time, sql);
            }

        } catch (Exception e) {
            log.error("[SQL]{}", sql);
            log.error("error", e);
            throw e;
        }

        return returnValue;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

    public static String getSql(String sql, String sqlId) {
        StringBuilder str = new StringBuilder(100);
        str.append(sqlId);
        str.append(":[");
        str.append(sql);
        str.append("]");
        return str.toString();
    }

    private static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");

        if (sql == null) {
            return null;
        }
        //批量插入不打印sql
        if (null != sql && sql.indexOf("insert") != -1 && sql.length() > 5000) {
            return sql;
        } else {
            if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) {
                TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
                if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
                } else {
                    MetaObject metaObject = configuration.newMetaObject(parameterObject);
                    for (ParameterMapping parameterMapping : parameterMappings) {
                        String propertyName = parameterMapping.getProperty();
                        if (metaObject.hasGetter(propertyName)) {
                            Object obj = metaObject.getValue(propertyName);
                            sql = sql.replaceFirst("\\?", getParameterValue(obj));
                        } else if (boundSql.hasAdditionalParameter(propertyName)) {
                            Object obj = boundSql.getAdditionalParameter(propertyName);
                            sql = sql.replaceFirst("\\?", getParameterValue(obj));
                        }
                    }
                }
            }
        }
        return sql;
    }
    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format((Date) obj) + "'";
        } else if (obj instanceof LocalDateTime) {
            String format = LocalDateTimeUtils.format((LocalDateTime) obj, LocalDateTimeUtils.DATE_TIME_PATTERN);
            value = "'" + format + "'";
        } else if (obj instanceof List) {
            value = (String) ((List) obj).stream().map(Object::toString).collect(joining(","));
        } else if (obj instanceof EnumSupport) {
            Byte index = ((EnumSupport) obj).value();
            value = index.toString();
        }else if (obj instanceof EnumSupportNumber){
            Integer index = ((EnumSupportNumber) obj).value();
            value = index.toString();
        }else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return  Matcher.quoteReplacement(value);
    }
}
